/*
 * Created on Jun 3, 2005
 *
 */
package com.erclab.internal.xpresso.handlers;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.*;

import com.erclab.internal.xpresso.exceptions.ReportException;
import com.erclab.internal.xpresso.reportelements.*;
import com.erclab.internal.xpresso.reports.Report;
import com.erclab.internal.xpresso.reports.ReportParameters;
import com.erclab.internal.xpresso.reports.ReportResultSet;

import org.apache.commons.dbutils.ResultSetHandler;

/**
 * @author Enrique Rodriguez.
 *
 */
public class ReportResultsHandler implements ResultSetHandler {

	private Report theReport;
	private ReportParameters parameters;
	private int columns;
	private String[] columnNames;

	public ReportResultsHandler(Report r){
		this.theReport = r;
		columns = r.getReportElements().size();
		this.columnNames = new String[columns];
		
		for (int i =0; i < columns; i++){
			columnNames[i] = ((ReportElement)r.getReportElements().get(i)).getColumnName();
		}
	}
	

	/* (non-Javadoc)
	 * @see org.apache.commons.dbutils.ResultSetHandler#handle(java.sql.ResultSet)
	 */
	public Object handle(ResultSet rs) throws SQLException {
		ReportResultSet rrs = new ReportResultSet(theReport);
		theReport.setReportResultSet(rrs);
		while (rs.next()){
			// Create new row
			String[] row = new String[columns];
			// Get the unique id for this row
			String uniqueKeyValue = rs.getString(theReport.getUniqueKeyName());
			// Loop through the formelements
			for (int i = 0; i< columns; i++){
				if (columnNames[i] != null && !columnNames[i].trim().equals("")) {
					try {
						row[i] = ((ReportElement)theReport.getReportElements().get(i)).toHTML(rs.getString(columnNames[i]), uniqueKeyValue, this.theReport);
					} catch (ReportException e) {
						throw new SQLException("The method toHTML() threw an exception: " + e);
					}
				} else {
					try {
						row[i] = ((ReportElement)theReport.getReportElements().get(i)).toHTML(null, uniqueKeyValue, this.theReport);
					} catch (ReportException e) {
						throw new SQLException("The method toHTML() threw an exception: " + e);
					}
				}
			}
			rrs.addRow(row, uniqueKeyValue);
		}
		return rrs;	
	}

}
